/*
 * Copyright 2003-2005 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */

#include <Types.h>
#include <dictionary/Dictionary.h>
#include <dictionary/DictionaryTypes.h>
#include <TypeBindCommon.h>

#include <util/ChunkBuffer.h>
#include <message/MessageReader.h>
#include <message/MessageWriter.h>

#include "../data/MixedData.h"
#include "MessageTest.h"

CPPUNIT_TEST_SUITE_REGISTRATION( MessageTest );


/* helpers file readers */
typedef struct file_data
{
	FILE * fd;
}
file_data;


int fileReader( type_input_stream * in, void * data, char * buffer, int size )
{
	file_data * fileData = (file_data *) data;

	return fread( buffer, 1, size, fileData->fd );	
}


void MessageTest::setUp()
{
	file_data fileData;
	reference_type_map core_map;
	type_map dictionary_map;
	int rc;
	
	type_library_init( &_library ); 
	rc = type_core_init( &_library );
	if ( rc != TYPE_OK )
	{
		printf( "failed to init core" );
		return;
	}
	
	rc = dictionary_types_init( &_library );
	if ( rc != TYPE_OK )
	{
		printf( "failed to init dictionary" );
		return;
	}
	
	reference_type_map_init( &core_map, &_library, NULL );
	type_map_core_init( &core_map );

	fileData.fd = fopen( "data\\common.dictionary","r" );
	if ( fileData.fd == NULL )
	{
		printf( "common.dictionary not found" );
		return;
	}
	
	type_map_init( &dictionary_map, &_library );
	
	rc = read_dictionary( &_library, fileReader, &fileData, &dictionary_map );
	if (rc != TYPE_OK )
	{
		printf( "failed to read meta.dictionary" );
		return;
	}
	
	rc = type_bind_common( &_library );
	if ( rc != TYPE_OK )
	{
		printf( "failed to bind common types\n" );
		return;
	}
	
	rc = mixed_data_register( &_library );
	if ( rc <= NOTYPE )
	{
		printf( "failed to register mixed data\n" );
		return;
	}

}

void MessageTest::testMessageLoop()
{
    mixed_data data;
	chunk_buffer buffer;
	
	mixed_data_init( &data, 234545, (short)234, "Testing");
		
	chunk_buffer_init( &buffer );
    int rc = write_message( &_library, chunkBufferWriter, &buffer, &mixed_data_name, &data );
    CPPUNIT_ASSERT( rc == TYPE_OK );
    chunk_buffer_close( &buffer );

	void * object;        
    rc = read_message( &_library, chunkBufferReader, &buffer, &object );
    CPPUNIT_ASSERT( rc == TYPE_OK );

    mixed_data * read_data = (mixed_data*) object;
    CPPUNIT_ASSERT( read_data->anInt == data.anInt );
    CPPUNIT_ASSERT( read_data->aShort == data.aShort );
    CPPUNIT_ASSERT( !strcmp( read_data->anAscii, data.anAscii ) );	
}
